//
//  creatOrderViewController.m
//  ZPSALE
//
//  Created by tmosport on 14-6-27.
//  Copyright (c) 2014年 tmosport. All rights reserved.
//

#import "creatOrderViewController.h"
#import "CartViewController.h"
#import "optionChooseViewController.h"
#import "invoiceViewController.h"
#import "goodsListViewController.h"
#import "addListTableViewController.h"
#import "submitViewController.h"
#import "MBProgressHUD.h"

@interface creatOrderViewController ()
@property(nonatomic,strong) NSDictionary *orderListsDic;
@property (strong, nonatomic) IBOutlet UILabel *needPay;
@property (strong, nonatomic) IBOutlet UIButton *submitBT;
@property (nonatomic,strong) UILabel *tips;

@property (nonatomic,retain) NSMutableDictionary *params;


@property (nonatomic,strong)NSString* paytypeid;//paytypeid:（1-货到2=在线4=线下）
@property (nonatomic,strong)NSString* addressid;
@property (nonatomic,strong)NSString*  shippingtime;//shippingtime:发货时间
@property (nonatomic,strong)NSString*  shipingTitle;//shippingtime:发货时间
@property (nonatomic,strong)NSString*  payTypeTitle;//shippingtime:发货时间
@property (nonatomic,strong)NSString*  invoicetype;//invoicetype:发票类型
@property (nonatomic,strong)NSString*  typeTitle;//itemTitle:发票类型描述
@property (nonatomic,strong)NSString*  itemTitle;//itemTitle:发票明细描述
@property (nonatomic,strong)NSString*  invoiceitem;//invoiceitem:发票明细
@property (nonatomic,strong)NSString*  invoicetitle;//invoicetitle:发票抬头

@property (nonatomic,strong)NSString* isusebalance;//是否使用余额（为空为不使用，1为使用）
@property (nonatomic,strong)NSString* totalamount;//totalamount:订单总额
@property (nonatomic,strong)NSString* needpay;//needpay:还需要支付的金额
@property (nonatomic,strong)NSString* ordermemo;//ordermemo:订单备注
@property(nonatomic,strong) NSDictionary *creatLogDic;

//productspcid:货品id
//premiumprice:手机专享 专享价格


@end

@implementation creatOrderViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //默认设置不开发票
    _invoicetype = @"3";
    _typeTitle = @"不开发票";
    
    [self setNavigationItem];
    [self setupItem];
    [self dataInit];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showShipping:) name:@"changeShippingTime" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showPayType:) name:@"changePayType" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showInvoice:) name:@"changeInvoiceInfo" object:nil];
}

- (void)setupItem
{
    self.title = @"确认订单";
    
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    [_submitBT.layer setCornerRadius:4.0];
    [_submitBT setBackgroundColor:ColorFromRGB(0xff0100)];
}

-(void)setNavigationItem {
    [self.navigationController.navigationBar setBackIndicatorImage:
     [UIImage imageNamed:@"return"]];
    [self.navigationController.navigationBar setBackIndicatorTransitionMaskImage:
     [UIImage imageNamed:@"return"]];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleBordered target:nil action:nil];
}

-(void)leftBarbuttonItemClicked:(UIButton *)button {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)showShipping:(NSNotification *)notification{
    // 取出notification的object
    NSDictionary *shipingDic;
    shipingDic = notification.object;
    _shipingTitle =shipingDic[@"shippingTitle"];
    _shippingtime = [NSString stringWithFormat:@"%@",shipingDic[@"id"]];
    //配送时间(@"%@",_shippingtime);
    [self.orderFormTV reloadData];
}

- (void)showPayType:(NSNotification *)notification{
    // 取出notification的object
    NSDictionary *payTypeDic;
    payTypeDic = notification.object;
    _payTypeTitle =payTypeDic[@"payTpyeTitle"];
    _paytypeid =  [NSString stringWithFormat:@"%@",payTypeDic[@"id"]];
    //支付方式(@"%@",_paytypeid);
    [self.orderFormTV reloadData];
    
}

- (void)showInvoice:(NSNotification *)notification{
    // 取出notification的object
    NSDictionary *invoiceInfo;
    invoiceInfo = notification.object;
   _invoicetype =invoiceInfo[@"invoiceType"];
    _typeTitle =invoiceInfo[@"typeTitle"];
    _itemTitle =invoiceInfo[@"itemTitle"];
    _invoicetitle =invoiceInfo[@"invocieTitle"];
     _invoiceitem =invoiceInfo[@"invocieItem"];
    //发票信息
     [self.orderFormTV reloadData];
}

- (void)dataInit{
    _params = [@{@"memberid": _memberId,
                             @"access_token": _atoken,
                 
                             @"isusebalance":([_isusebalance length] == 0||[_isusebalance isEqual:[NSNull null]]) ? @"" : _isusebalance,
                             @"source": @"5",
                             @"productspcid":([_productSpcid length] == 0||[_productSpcid isEqual:[NSNull null]]) ? @"" : _productSpcid,
                            @"premiumprice":([_premiumprice length] == 0||[_premiumprice isEqual:[NSNull null]]) ? @"" : _premiumprice
                             }mutableCopy];
   
    if ([_productSpcid length] == 0||[_productSpcid isEqual:[NSNull null]]) {
        //非立即购买
    }else{
         [_params setObject:_productSpcid forKey:@"productspcid"];
    };

    
        if ([_isusebalance length] == 0||[_isusebalance isEqual:[NSNull null]]){
        [_params removeObjectForKey:@"isusebalance"];
    };
    if ([_productSpcid length] == 0||[_productSpcid isEqual:[NSNull null]]) {
        [_params removeObjectForKey:@"productspcid"];
    };
    if ([_premiumprice length] == 0||[_premiumprice isEqual:[NSNull null]]) {
        [_params removeObjectForKey:@"premiumprice"];
    };
    
    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.dimBackground = NO;
    HUD.labelText = @"更新数据中";

    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger POST:APIURL@"sale/initOrder.json" parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _orderListsDic = (NSDictionary *)responseObject;

        [HUD showAnimated:YES whileExecutingBlock:^{
            HUD.mode = MBProgressHUDModeText;
        }completionBlock:^{
            [self addrViewreFresh];
            [self totalMountFresh];
            [self.orderFormTV reloadData];
            [HUD hide:YES afterDelay:1];

        }];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //DO:错误捕获
        [HUD hide:YES afterDelay:1];
    }];
}

- (void)addrViewreFresh
{
    NSDictionary *addrDic = _orderListsDic[@"defaultMemberAddr"];

    if ([addrDic isEqual:[NSNull null]]) {

        if (!_tips) {
            _tips = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 110)];
            _tips.textAlignment = NSTextAlignmentCenter;
            _tips.font = [UIFont fontWithName:@"Helvetica" size:15];
            _tips.textColor = ColorFromRGB(0x333333);
            _tips.text = @"请点击此处以添加或选择收货地址>>>";
            _addrView.backgroundColor =  [UIColor whiteColor];
            [_addrView addSubview:_tips];
        }
        [_tips setHidden:NO];
    }else{
        [_tips setHidden:YES];
        _addrView.backgroundColor = ColorFromRGB(0xff0100);
        UILabel *reciveName = (UILabel *)[_addrView viewWithTag:1000];
        UILabel *phone = (UILabel *)[_addrView viewWithTag:1001];
        UILabel *address = (UILabel *)[_addrView viewWithTag:1002];
        NSString *addressString = [NSString stringWithFormat:@"%@,%@,%@,%@",addrDic[@"province"],addrDic[@"city"],addrDic[@"town"],addrDic[@"address"]];
        phone.text = [NSString stringWithFormat:@"%@",addrDic[@"phone"]];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
        [paragraphStyle setLineSpacing: 3];
        
        NSDictionary *attributes = @{NSParagraphStyleAttributeName: paragraphStyle};
        
        NSAttributedString *attributedString = [[NSAttributedString alloc] initWithString:addressString attributes:attributes];
        
        [address setAttributedText: attributedString];
//        address.text = addressString;
        reciveName.text = [NSString stringWithFormat:@"%@",addrDic[@"receiver"]];
        _addressid =  [NSString stringWithFormat:@"%@",addrDic[@"addrId"]];
    }
    UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [_addrView addGestureRecognizer:singleTap];
}
-(void)handleSingleTap:(UITapGestureRecognizer *)sender
{
    addListTableViewController *addListVC = [self.storyboard instantiateViewControllerWithIdentifier:@"addListTableViewController"];
    addListVC.memberId = _memberId;
    addListVC.token = _atoken;
    [self.navigationController pushViewController:addListVC animated:YES];
}

- (void)totalMountFresh
{
    _needpay = [NSString stringWithFormat:@"%@",_orderListsDic[@"needPay"]];
    NSInteger money = [_orderListsDic[@"money"] intValue];
//    NSString *mountString = [NSString stringWithFormat:@"￥%d",money];
    _totalamount=[NSString stringWithFormat:@"%d",money];
    _needPay.text = [NSString stringWithFormat:@"￥%@",_orderListsDic[@"needPay"]];
}


#pragma mark -TableviewDatasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell;
    NSInteger section =  indexPath.section;
    if (section == 0) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"commonCell"];
            UILabel *title = (UILabel *)[cell viewWithTag:1000];
            UILabel *detail = (UILabel *)[cell viewWithTag:1001];
            title.text = @"支付方式";

            NSString *detailString = [_paytypeid intValue] > 0? [NSString stringWithFormat:@"%@",_payTypeTitle] : @"请选择";
            detail.text = detailString;
        }
    }
    if (section == 1) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"commonCell"];
            UILabel *title = (UILabel *)[cell viewWithTag:1000];
            UILabel *detail = (UILabel *)[cell viewWithTag:1001];
            title.text = @"配送时间";
            NSString *detailString = [_shippingtime intValue] > 0? [NSString stringWithFormat:@"%@",_shipingTitle] : @"请选择";
            detail.text = detailString;
        }
    }
    if (section == 2) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"titleCell"];
            UILabel *iType = (UILabel *)[cell viewWithTag:1001];
            UILabel *iTitle = (UILabel *)[cell viewWithTag:1003];
            UILabel *iItem = (UILabel *)[cell viewWithTag:1002];
            iType.text = _typeTitle;
            iTitle.text = _invoicetitle;
            iItem.text = _itemTitle;
        }
    }
    if (section ==3) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"inputCell"];
            UITextField *memInfo = (UITextField *)[cell viewWithTag:1001];
            memInfo.delegate = self;
        }
    }
   
    
    if (section ==4) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"commonCell"];
             cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            UILabel *title = (UILabel *)[cell viewWithTag:1000];
            UILabel *detail = (UILabel *)[cell viewWithTag:1001];
            title.text = @"商品清单";
            detail.text = @"";
        }
    }
    if (section ==5) {
        cell = nil;
        if (!cell) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"infoCell"];
            UILabel *totalmount = (UILabel *)[cell viewWithTag:1001];
            UILabel *discountnum = (UILabel *)[cell viewWithTag:1002];
            totalmount.text = [NSString stringWithFormat:@"￥%@",_orderListsDic[@"money"]];
           discountnum.text = [NSString stringWithFormat:@"￥%@",_orderListsDic[@"favorableMoney"]];
        }
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        optionChooseViewController *ocVC = [self.storyboard instantiateViewControllerWithIdentifier:@"optionChooseViewController"];
        ocVC.sourceType = 1;
        ocVC.totalCount = [_orderListsDic[@"needPay"] intValue];
        ocVC.chooseId = [_paytypeid intValue];
        [self.navigationController pushViewController:ocVC animated:YES];
    }else if (indexPath.section == 1){
        optionChooseViewController *ocVC = [self.storyboard instantiateViewControllerWithIdentifier:@"optionChooseViewController"];
        ocVC.sourceType = 2;
        ocVC.chooseId = [_shippingtime intValue];
        [self.navigationController pushViewController:ocVC animated:YES];
    }else if (indexPath.section == 2){
        invoiceViewController *invoiceVC = [self.storyboard instantiateViewControllerWithIdentifier:@"invoiceViewController"];
        invoiceVC.invoiceType=_invoicetype;
        invoiceVC.invoiceItem = _invoiceitem;
        invoiceVC.invoiceTitle = _invoicetitle;
        invoiceVC.memberId = _memberId;
        invoiceVC.token = _atoken;
        [self.navigationController pushViewController:invoiceVC animated:YES];
    }else if (indexPath.section == 3){
        
    }else if (indexPath.section == 4){
        if ([_productSpcid intValue]>0) {
                //DO:立即购买跳转
        }else{
            goodsListViewController *goodsListVc = [self.storyboard instantiateViewControllerWithIdentifier:@"goodsListViewController"];
            goodsListVc.memberId = _memberId;
            goodsListVc.atoken = _atoken;
            [self.navigationController pushViewController:goodsListVc animated:YES];
        }
        

    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 2) {
        return 92;
    }else if(indexPath.section == 5){
        return 71;
    }else{
        return 44;
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated]; // 这句话很重要
    self.navigationController.navigationBarHidden = NO;
    [self dataInit];
}

#pragma mark -UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    footView.backgroundColor = [UIColor clearColor];
    self.orderFormTV.tableFooterView = footView;
    [self.orderFormTV scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:4] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    _ordermemo = textField.text;
    self.orderFormTV.tableFooterView = nil;
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)dealloc{
    // 消息发送完,要移除掉
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeShippingTime" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changePayType" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeInvoiceInfo" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"useCard" object:nil];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)createOrder:(UIButton *)sender {
    sender.enabled = NO;
    if ([_paytypeid length] == 0 ||[_paytypeid isEqual:[NSNull null]]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确选择支付方式" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_shippingtime length] == 0 || [_shippingtime isEqual:[NSNull null]] ) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确选择配送时间" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_addressid length] == 0 ||[_addressid isEqual:[NSNull null]]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确选择收货地址" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }
    if ([_invoicetype length] == 0 ||[_invoicetype isEqual:[NSNull null]]) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确选择发票信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alertView show];
        return;
    }else{
        if ([_invoicetype intValue] == 1) {
            //判断个人发票类型
            if ([_invoicetype length] == 0 ||[_invoicetype isEqual:[NSNull null]] ||[_invoiceitem length] == 0 ||[_invoiceitem isEqual:[NSNull null]]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确选择发票信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                return;
            }else{
                [_params setObject:_invoicetype forKey:@"invoicetype"];//发票类型
                [_params setObject:_invoiceitem forKey:@"invoiceitem"];//发票明细
            }
        }
        if ([_invoicetype intValue] == 2) {
            //判断公司发票类型
            if ([_invoicetype length] == 0 ||[_invoicetype isEqual:[NSNull null]] ||[_invoiceitem length] == 0 ||[_invoiceitem isEqual:[NSNull null]]||[_invoicetitle length] == 0 ||[_invoicetitle isEqual:[NSNull null]]) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确填写发票信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                return;
            }else{
                [_params setObject:_invoicetype forKey:@"invoicetype"];//发票类型
                [_params setObject:_invoiceitem forKey:@"invoiceitem"];//发票明细
                [_params setObject:_invoicetitle forKey:@"invoicetitle"];//发票抬头
            }
        }
        if ([_invoicetype intValue] == 3) {
            //判断公司发票类型
            if ([_invoicetype length] == 0 ||[_invoicetype isEqual:[NSNull null]] ) {
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提交失败" message:@"请正确填写发票信息" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alertView show];
                return;
            }else{
                [_params setObject:_invoicetype forKey:@"invoicetype"];//发票类型
            }
        }
    }
    
    if ([_ordermemo length] == 0 ||[_ordermemo isEqual:[NSNull null]]) {
        //备注预留
    }else{
        [_params setObject:_ordermemo forKey:@"ordermemo"];//订单备注
    }
    [_params setObject:_paytypeid forKey:@"paytypeid"];//支付类型
    [_params setObject:_addressid forKey:@"addressid"];//收获地址id
    [_params setObject:_shippingtime forKey:@"shippingtime"];//发货时间
    [_params setObject:_totalamount forKey:@"totalamount"];//订单总额
    [_params setObject:_needpay forKey:@"needpay"];//needpay
    AFHTTPRequestOperationManager *manger = [AFHTTPRequestOperationManager manager];
    [manger POST:APIURL@"sale/creatOrder.json" parameters:_params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        _creatLogDic = (NSDictionary *)responseObject;
        NSString *orderSn;
        NSString *orderId ;
        NSString *orderMemo;
        NSString *needPay;
        NSInteger payStatus;
        if ([_creatLogDic[@"orderId"] intValue] > 0) {
            orderMemo = @" ";
            orderId = [NSString stringWithFormat:@"%@",_creatLogDic[@"orderId"]];
            orderMemo = [NSString stringWithFormat:@"%@",_creatLogDic[@"orderMemo"]];
            orderSn = [NSString stringWithFormat:@"%@",_creatLogDic[@"orderSn"]];
            needPay = [NSString stringWithFormat:@"%@",_creatLogDic[@"needPay"]];
            payStatus = [_creatLogDic[@"payStatus"] integerValue];
        }
//        NSMutableDictionary *orderInfo =[@{
//                                       @"paytypeid": _paytypeid,
//                                       @"paytypetitle": _payTypeTitle,
//                                       @"shippingtime": _shipingTitle,
//                                       @"needpay":_needpay,
//                                       @"source":@"3",
//                                       }mutableCopy];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
        NSArray *orderInfoArr = [NSArray arrayWithObjects:orderSn,needPay,_payTypeTitle, _shipingTitle, orderMemo,_paytypeid,orderId,nil];
        submitViewController *submitVc = [self.storyboard instantiateViewControllerWithIdentifier:@"submitViewController"];
        NSLog(@"orderinfo :%@",orderInfoArr);
        submitVc.memberId = _memberId;
        submitVc.token = _atoken;
        submitVc.orderInfo = orderInfoArr;
        submitVc.payStatus = payStatus;
        submitVc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:submitVc animated:YES];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        sender.enabled = YES;
        //DO:(@"Error:%@", error);
    }];
    
}
@end
